import React, {Component} from 'react';
import {
  FlatList,
  Text,
  View,
  StyleSheet,
  ActivityIndicator,
  TouchableOpacity,
} from 'react-native';
import {connect} from 'react-redux';
import {createMaterialTopTabNavigator} from '@react-navigation/material-top-tabs';
import {RefreshControl} from 'react-native-gesture-handler';
import Toast from 'react-native-easy-toast';
import Ionicons from 'react-native-vector-icons/Ionicons';

import actions from '../action/index';
import TrendingItem from '../common/TrendingItem';
import NavigationBar from '../common/NavigationBar';
import AnalyticsUtil from '../util/AnalyticsUtil';
import NavigationUtil from '../navigator/NavigationUtil';

const Tab = createMaterialTopTabNavigator();
const tabNames = ['Vue', 'Java', 'PHP', 'typescript'];
const URL = 'https://github.com/trending/';
const THEME_COLOR = '#678';
const pageSize = 10;

class TrendingPage extends Component {
  constructor(props) {
    super(props);
  }

  renderRightButton() {
    const {theme} = this.props;
    return (
      <TouchableOpacity
        onPress={() => {
          //新版本友盟SDK 时间统计方法由 track -> onEvent
          AnalyticsUtil.onEvent('SearchButtonClick');
          NavigationUtil.goPage({theme}, 'SearchPage');
        }}>
        <View style={{padding: 5, marginRight: 8}}>
          <Ionicons
            name={'ios-search'}
            size={24}
            style={{
              marginRight: 8,
              alignSelf: 'center',
              color: 'white',
            }}
          />
        </View>
      </TouchableOpacity>
    );
  }

  render() {
    const {theme} = this.props;
    let statusBar = {
      backgroundColor: theme.themeColor,
      barStyle: 'light-content',
    };
    let navigationBar = (
      <NavigationBar
        title={'趋势'}
        statusBar={statusBar}
        rightButton={this.renderRightButton()}
        style={theme.styles.navBar}
      />
    );
    return (
      <View style={styles.container}>
        {navigationBar}
        <Tab.Navigator
          screenOptions={{
            tabBarLabelStyle: styles.tabBarLabelStyle,
            tabBarItemStyle: styles.tabBarItemStyle,
            tabBarIndicatorStyle: styles.tabBarIndicatorStyle,
            style: styles.tabScreenStyle,
            tabBarScrollEnabled: true,
          }}>
          {tabNames.map(item => {
            return (
              <Tab.Screen
                key={item}
                name={item}
                component={TrendingTabPage}
                initialParams={{storeName: item}}
              />
            );
          })}
        </Tab.Navigator>
      </View>
    );
  }
}

class TrendingTab extends Component {
  constructor(props) {
    super(props);
    this.storeName = this.props.route.params.storeName;
    this.state = {};
  }

  componentDidMount() {
    this.loadData();
  }

  genFetchUrl(key) {
    return URL + key + '?since=daily';
  }

  /**
   * 获取与当前页面有关的数据
   * @returns {*}
   * @private
   */
  _store() {
    const {trending} = this.props;
    let store = trending[this.storeName];
    if (!store) {
      store = {
        items: [],
        isLoading: false,
        projectModels: [], //要显示的数据
        hideLoadingMore: true, //默认隐藏加载更多
      };
    }
    return store;
  }

  genIndicator() {
    return this._store().hideLoadingMore ? null : (
      <View style={styles.indicatorContainer}>
        <ActivityIndicator style={styles.indicator} />
        <Text>正在加载更多</Text>
      </View>
    );
  }

  loadData(loadMore) {
    const {onRefreshTrending, onLoadMoreTrending} = this.props;
    const store = this._store();
    const url = this.genFetchUrl(this.storeName);
    if (loadMore) {
      onLoadMoreTrending(
        this.storeName,
        ++store.pageIndex,
        pageSize,
        store.items,
        callback => {
          this.refs.toast.show('没有更多了！');
        },
      );
    } else {
      onRefreshTrending(this.storeName, url, pageSize);
    }
  }

  renderItem(data) {
    const item = data.item;
    const {theme} = this.props;
    return <TrendingItem projectModel={item} theme={theme} />;
  }

  render() {
    const store = this._store();
    return (
      <View>
        <FlatList
          data={store.projectModels}
          renderItem={data => this.renderItem(data)}
          keyExtractor={item => '' + item.id}
          refreshControl={
            <RefreshControl
              title="Loading"
              titleColor={THEME_COLOR}
              colors={[THEME_COLOR]}
              refreshing={store.isLoading}
              onRefresh={() => this.loadData()}
              tintColor={THEME_COLOR}
            />
          }
          ListFooterComponent={() => this.genIndicator()}
          onEndReached={() => {
            setTimeout(() => {
              if (this.canLoadMore) {
                this.loadData(true);
                this.canLoadMore = false;
              }
            }, 100);
          }}
          onEndReachedThreshold={0.5}
          onMomentumScrollBegin={() => {
            this.canLoadMore = true;
          }}
        />
        <Toast ref={'toast'} position={'center'} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  tabBarItemStyle: {
    minWidth: 50,
  },
  tabBarIndicatorStyle: {
    height: 2,
  },
  tabScreenStyle: {
    backgroundColor: '#a67',
  },
  tabBarLabelStyle: {
    fontSize: 13,
    marginTop: 6,
    marginBottom: 6,
  },
  indicatorContainer: {
    alignItems: 'center',
  },
  indicator: {
    color: 'red',
    margin: 10,
  },
});

const mapStateToProps = state => ({
  trending: state.trending,
  theme: state.theme.theme,
});
const mapDispatchToProps = dispatch => ({
  onRefreshTrending: (storeName, url, pageSize) =>
    dispatch(actions.onRefreshTrending(storeName, url, pageSize)),
  onLoadMoreTrending: (storeName, pageIndex, pageSize, items, callBack) =>
    dispatch(
      actions.onLoadMoreTrending(
        storeName,
        pageIndex,
        pageSize,
        items,
        callBack,
      ),
    ),
});
const TrendingTabPage = connect(
  mapStateToProps,
  mapDispatchToProps,
)(TrendingTab);

const mapTrendingStateToProps = state => ({
  theme: state.theme.theme,
});
const mapTrendingDispatchToProps = dispatch => ({});

export default connect(
  mapTrendingStateToProps,
  mapTrendingDispatchToProps,
)(TrendingPage);
